import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

 import * as CustomerContactAction from '../actions/customerContact'

 import ViewContactLog from './data/ViewContactLog'

import { WeaErrorPage, WeaTools,WeaTextarea ,WeaBrowser,WeaUpload,WeaNewScroll,WeaRightMenu  } from 'ecCom'
import {Button,Select,Icon,Form, Input,Modal,Spin,Row,Col} from "antd";
const Option = Select.Option;
const FormItem = Form.Item;
const createForm = Form.create;
import Immutable from 'immutable'
const is = Immutable.is;
import equal from 'deep-equal'

class CustomerContact extends React.Component {
	constructor(props) {
		super(props);
        this.state={
            direction:"down",
            ascSort:true,
            hasFile:"true",
            relatedfile:"",
            isrefresh:0
        }
	}
	
    componentDidMount() {
        //一些初始化请求
        const { actions,params,location } = this.props;
        let fromUrl = {}; 
        if(location && JSON.stringify(location.query)!=="{}"){
            fromUrl = location.query;  
        } 
        const newBaseParams = {...params,...fromUrl};
        actions.initDatas(newBaseParams);

        actions.getContacter({from:newBaseParams.from,customerId:newBaseParams.customerId});
        actions.getSellChance({from:newBaseParams.from,customerId:newBaseParams.customerId});

        actions.getRightMenu({selectType:'contactinfo',customerId:newBaseParams.customerId});  
    }
    shouldComponentUpdate(nextProps, nextState) {
		//组件渲染控制
		return !is(this.props.loading,nextProps.loading)||
        !is(this.props.params,nextProps.params)||
        !is(this.props.viewlogs,nextProps.viewlogs)||
        !is(this.state.ascSort,nextState.ascSort)||
        !is(this.state,nextState)||
        !is(this.props.contacterInfo,nextProps.contacterInfo)||
        !is(this.props.sellChanceInfo,nextProps.sellChanceInfo)||
        !is(this.props.customerContactRcList,nextProps.customerContactRcList)||
        !is(this.props.contactFields,nextProps.contactFields)||
        !is(this.props.rowHeight,nextProps.rowHeight);
    }
    componentWillReceiveProps(nextProps) {
         const oldParams = this.props.params;
         const newParams = nextProps.params;
         if(!equal(oldParams,newParams)){
             const { actions,params ,location} =nextProps;
             let fromUrl = {}; 
             if(location && JSON.stringify(location.query)!=="{}"){
                 fromUrl = location.query;  
             } 
             const newBaseParams = {...params,...fromUrl};
             actions.initDatas(newBaseParams); 
             actions.getContacter({from:newBaseParams.from,customerId:newBaseParams.customerId});
             actions.getSellChance({from:newBaseParams.from,customerId:newBaseParams.customerId});

             actions.getRightMenu({selectType:'contactinfo',customerId:newBaseParams.customerId});
         }
     }
	componentWillUnmount() {
		//组件卸载时一般清理一些状态

	}
	render() {
		const { loading, title,customerId,viewlogs,contacterInfo,sellChanceInfo,type,rowHeight } = this.props;
        const {direction,value,ascSort,isrefresh} = this.state;
        const {getFieldProps} = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };
		return (
            <div className="customer-contact" >
                <WeaRightMenu datas={this.getCusContactRightMenu()} onClick={this.onCusContactRightMenuClick.bind(this)}>
                    <div>
                    <Form horizontal >
                        <Row >
                            <Col span="24" style={{marginBottom:"5px"}}>
                                <Input type="textarea" {...getFieldProps("ContactInfo", {
                                    initialValue:""})} placeholder="请填写联系人记录" rows={rowHeight} onFocus={this.textOnFocus} />
                            </Col>
                        </Row>
                        <Row className="customer-contact-header" style={{display:rowHeight == "1" ? "none":"block"}}>
                            <Col span="24" >
                                <Button type="primary" size="small" onClick={()=>this.submitContacts()}>提交</Button>
                                <Button type="ghost" size="small">安排计划</Button>
                                <Select {...getFieldProps("contacterId", {initialValue:"-联系人-"})}  style={{width:90,marginRight:'10px'}} size="small">
                                    <Option value="" key="1-1" title="联系人">-联系人-</Option>
                                    {this.getContacterOption()}
                                </Select>
                                {  type != "sellchance" &&
                                    <Select {...getFieldProps("sellChanceId", {initialValue:"-商机-"})}  style={{width:90,marginRight:'10px'}} size="small" >
                                        <Option value="" key="1-1" title="商机">-商机-</Option>
                                        {this.getSellChanceOption() }
                                    </Select>
                                }
                                <span className="customer-contact-group-addition" style={{float:"right"}}><span style={{marginRight:5}} onClick={this.showBrowsers}>附加信息</span><Icon type={direction} /></span>
                            </Col>
                        </Row>
                        <Row style={{display:direction == "down" ? "none":"block"}}>
                            <Col span="24" >
                                <FormItem
                                    label={"相关文档"}
                                    {...formItemLayout}>
                                    <WeaBrowser {...getFieldProps('relateddoc', { initialValue: '' })}  type={9} title="文档" hasAdvanceSerach={true} isSingle={false} />
                                </FormItem>
                                <FormItem
                                    label={"相关流程"}
                                    {...formItemLayout}>
                                    <WeaBrowser {...getFieldProps('relatedwf', { initialValue: '' })} type={16} title="流程" hasAdvanceSerach={true} isSingle={false} />
                                </FormItem>
                                <FormItem
                                    label={"相关项目"}
                                    {...formItemLayout}>
                                    <WeaBrowser {...getFieldProps('relatedprj', { initialValue: '' })} type={8} title="项目" hasAdvanceSerach={true} isSingle={false} />
                                </FormItem>
                                <FormItem
                                    label={"相关附件"}
                                    {...formItemLayout}>
                                    <WeaUpload 
                                        key={isrefresh}
                                        uploadId="relatedfile"
                                        uploadUrl="/api/crm/common/fileUpload"
                                        category="0,0,0"
                                        autoUpload={false}
                                        showBatchLoad={false}
                                        showClearAll={false}
                                        multiSelection={true}
                                        datas={[]}
                                        viewAttr={3}
                                        onChange={this.fileUploadBack}
                                        onUploading={(state)=>this.hsaUploadState(state)}
                                    />
                                </FormItem>
                            </Col>
                        </Row>
                        </Form>
                        <div className="customer-contact-bottomline"></div>
                        <div className="customer-contact-sort">
                            <Spin spinning={loading} />
                            <div onClick={this.sortByAsc} className="customer-contact-sort-asc" style={{ background: `url(/spa/crm/images/icon_sequence_${ascSort ? "":"h_"}e9.png)`}}></div>
                            <div onClick={this.sortByDesc} className="customer-contact-sort-asc" style={{ background: `url(/spa/crm/images/icon_reverse_${ascSort ? "h_":""}e9.png)`}}></div>
                        </div>
                    </div>
                    <div className="customer-contact-content" onClick={this.textOnBlur}>
                        <div id="viewLogs" style={{height:"100%",overflow: "auto",paddingBottom:"32px"}}>
                             <WeaNewScroll height={"100%"} children={<ViewContactLog data={viewlogs}/>} />
                        </div>
                    </div>
                </WeaRightMenu>
            </div>
		)
    }
    textOnFocus=()=>{
        const {actions  } = this.props;
        actions.changeTextHeight(4);
    }
    textOnBlur=()=>{
        const {actions ,contactFields } = this.props;
        const value = contactFields.get('ContactInfo') && contactFields.get('ContactInfo').get('value') || "";
        if(!value){
             actions.changeTextHeight(1);
             this.setState({direction:"down"});
        }
    }
    showBrowsers=()=>{
        const {direction} = this.state;
        if(direction=="down"){
            this.setState({direction:"up"});
        }else{
            this.setState({direction:"down"});
        }
    }
    sortByDesc=()=>{
        const { actions,params,customerId } = this.props;
         this.setState({ascSort:true});
        actions.initDatas({...params,customerId:customerId,orderway:0});
    }
     sortByAsc=()=>{
        const { actions,params,customerId } = this.props;
        this.setState({ascSort:false});
        actions.initDatas({...params,customerId:customerId,orderway:1});
    }
    getContacterOption(){
        const {contacterInfo} = this.props;
        let children = [];
        contacterInfo.toJS().map(item =>{
            children.push(<Option value={item.contacterid} key={item.contacterid} title={item.firstname}>{item.firstname}</Option>)
        })
        return children
    }
    getSellChanceOption(){
        const {sellChanceInfo} = this.props;
        let children = [];
        sellChanceInfo.toJS().map(item =>{
            children.push(<Option value={item.sellchanceid} key={item.sellchanceid} title={item.subject}>{item.subject}</Option>)
        })
        return children
    }
    
    hsaUploadState=(state)=>{
        this.setState({hasFile:state});
    }
    fileUploadBack=(ids)=>{
        this.setState({relatedfile:`${ids}`});
       this.submitContacts(ids);
    }
    submitContacts=(ids)=>{
        let {params,actions,customerId,contactFields}  =this.props;
        const value = contactFields.get('ContactInfo') && contactFields.get('ContactInfo').get('value') || "";
        if(this.state.hasFile == "false"){ window.startUploadAll(); }else{
            if(value){
                const content= {
                    customerId:params.customerId || customerId,
                    sellChanceId:params.chanceid || contactFields.get('sellChanceId') && contactFields.get('sellChanceId').get('value') || "",
                    contacterId:contactFields.get('contacterId') && contactFields.get('contacterId').get('value') || "",
                    ContactInfo:value,
                    relateddoc:contactFields.get('relateddoc') && contactFields.get('relateddoc').get('value') || "",
                    relatedwf:contactFields.get('relatedwf') && contactFields.get('relatedwf').get('value') || "",
                    relatedprj:contactFields.get('relatedprj') && contactFields.get('relatedprj').get('value') || "",
                    relatedfile:ids ||"",
                };
                if(!params){
                    params={from:"all",customerId:customerId}
                }
                 actions.saveContacts(content,{...{from:"all",customerId:customerId},...params});
                 this.setState({direction:"down",isrefresh:this.state.isrefresh+1});
            }else{
                 Modal.info({
                    title: '系统提示',
                    content: '请填写联系记录！',
                });
            }
        }
    }
   
    getCusContactRightMenu(){
        const {customerContactRcList } = this.props;
        let btnArr = [];
        customerContactRcList && !is(customerContactRcList,Immutable.fromJS([])) && customerContactRcList.map(m=>{
            btnArr.push({
                icon: <i className={m.get('menuIcon')} />,
                content: m.get('menuName'),
                disabled : false
            })
        });
    	return btnArr
    }
    onCusContactRightMenuClick(){

    }
}

//组件检错机制
class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return(
			<WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
		);
	}
}

CustomerContact = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(CustomerContact);

//form 表单与 redux 双向绑定
CustomerContact = createForm({
	onFieldsChange(props, fields) {
		props.actions.saveContactFields({ ...props.contactFields.toJS(), ...fields });
	},
	mapPropsToFields(props) {
		return props.contactFields.toJS();
	}
})(CustomerContact);


// 把 state map 到组件的 props 上
const mapStateToProps = state => {
    const { crmcustomerContact} = state;
	return { 
        loading: crmcustomerContact.get('loading'),
        viewlogs:crmcustomerContact.get('viewlogs'),
        contacterInfo:crmcustomerContact.get('contacterInfo'),
        sellChanceInfo:crmcustomerContact.get('sellChanceInfo'),
        customerId:crmcustomerContact.get('customerId'),
        customerContactRcList:crmcustomerContact.get('customerContactRcList'),
        contactFields:crmcustomerContact.get('contactFields'),
        rowHeight:crmcustomerContact.get('rowHeight')
    }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
	return {
		actions: bindActionCreators(CustomerContactAction, dispatch)
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(CustomerContact);